import http from './http'

const globalDownloadUrl = ''
const baseUrl = '/api'

export function $asPost(url, data, contentType) {
  let ct = contentType || 'application/json;charset=UTF-8'
  let str = '?'
  for (let key in data) {
    str += key + '=' + data[key] + '&'
  }
  str = str.replace(/&$/gi, '')
  return http({
    method: 'post',
    url: baseUrl + url + str,
    headers: { 'Content-Type': ct }
  })
}

export function $post(url, data, contentType, config = {}) {
  let ct = contentType || 'application/json;charset=UTF-8'
  return http({
    method: 'post',
    url: baseUrl + url,
    data: data,
    headers: { 'Content-Type': ct },
    ...config
  })
}

export function $get(url, data, contentType, config = {}) {
  console.log(config,"config");
  let ct = contentType || 'application/x-www-form-urlencoded;charset=UTF-8'
  data = data || {}
  return http({
    method: 'get',
    url: baseUrl + url,
    params: data,
    headers: {
      'Content-Type': ct
    },
    ...config
  })
}

export function $getBlob(url, data, contentType) {
  let ct = contentType || 'application/x-www-form-urlencoded;charset=UTF-8'
  data = data || {}
  for (let key in data) {
    data[key] = encodeURI(data[key])
  }
  return http({
    method: 'get',
    url: baseUrl + url,
    params: data,
    responseType: 'blob',
    headers: {
      'Content-Type': ct
    }
  })
}

export function $downloadFile(blob) {
  if (!blob) {
    alert('链接为空，请检查！')
    return
  } else {
    blob = globalDownloadUrl + blob.substring(0, blob.lastIndexOf('.'))
  }
  window.open(blob)
}
